const {AsyncSeriesBailHook} = require('tapable'); 

// 创建readline对象，监听控制台输入
const readline = require('../../common/inputListener');

const git = require('../git/index');

const error = require('../../common/error');

// 在gulp压缩完成后的git操作

/**
 * 
 * @param {*} msg readline 输入的消息
 * @param {*} resolve promise 的resolve
 * @param {*} reject promise reject
 * @param {*} reOperator 回调函数
 * @param {*} operatorName 操作名
 * @param {*} rl readline的实例
 */
function rlFun(msg,resolve,reject,reOperator,operatorName,rl){
  
  if(msg === 'quit') reject('用户输入quit，');

  if(msg === 'yes') {

    let {result} = reOperator();

    if(result){

      resolve();

    }else{

      reject(operatorName+'操作失败，请检查，程序退出');

    }

  } else {
    
    console.log('请输入yes继续，quit退出程序');

  };
}

/**
 * 创建M分支
 * @param {*} msg 输入的指令
 * @param {*} resolve promise的resolve
 * @param {*} reject promise的reject
 * @param {*} rl readline实例
 */
function createMBranch(msg,resolve,reject,branch,rl){

  if(msg === 'quit') reject();

  let branchName = branch?'M'+branch.substr(1):branch;

  if(msg === 'yes') {

    let {result} = git.createMBranch();

    if(!result){
      
      reject(`创建${branchName}分支操作失败，`);

      return

    }
    
    if(!git.checkoutToM().result){

      reject(`切换${branchName}分支操作失败，`);

      return

    };

    if(!git.push(['push','--set-upstream','origin',branchName]).result){

      reject(`推送${branchName}分支操作失败，`);

      return
    }  
      
    resolve();

  } else {
    
    console.log(`请输入yes创建${branchName}，quit退出程序`);

  };
}

module.exports =  async function ({config={},tagName,lastVersionTag}){

  let gitOperatorHook = new AsyncSeriesBailHook();

  // let finishFlag = false;

  let rl;

  gitOperatorHook.tapPromise('pull',()=>{

    return new Promise((resolve, reject)=>{

      rl = readline.init();

      // 推送压缩后的代码
      let {result} = git.pull();

      if(!result) {

        rl.on('line', input => {

          rlFun(input,resolve,reject,git.pull,'git pull',rl);

        });

        rl.question('git pull 失败是否重新拉取？输入yes重新执行，quit退出程序:', answer => {
          
          rlFun(answer,resolve,reject,git.pull,'git pull',rl);

        });

      }else {
        
        resolve();

      }

    });
    
  });

  gitOperatorHook.tapPromise('add',()=>{

    return new Promise((resolve, reject)=>{
      
      let {result} = git.add();

      if(!result) {

        reject('git add 操作失败');

      }else {

        resolve();

      }

    });

  });

  gitOperatorHook.tapPromise('commit',()=>{
    
    return new Promise((resolve, reject)=>{

      let {result} = git.commit(config.commit);

      if(!result) {

        reject('git commit 操作失败');

      }else{

        resolve();

      }

    });

  });

  gitOperatorHook.tapPromise('push',()=>{
    
    return new Promise((resolve, reject)=>{

      rl.close();

      rl = readline.init();
      
      let {result} = git.push();

      if(!result) {

        rl.on('line',input=>{

          rlFun(input,resolve,reject,git.push,'git push',rl);

        });

        rl.question('git push 失败是否重新推送？输入yes重新执行，quit退出程序:',answer=>{

          rlFun(answer,resolve,reject,git.push,'git push',rl);

        });

      }else {
        
        resolve();

      }

    });

  });

  gitOperatorHook.tapPromise('checkoutToM',()=>{
    
    return new Promise((resolve, reject)=>{

      rl.close();

      rl = readline.init();
      
      // 切换分支到M
      let {result}=git.checkoutToM();
      
      let { branch } = git.getLocalBranch();

      if(!branch){

        reject('获取分支错误！');

        return

      };

      if(!result) {

        // 没有M分支 创建M分支推送至远端
        rl.on('line',input=>{

          createMBranch(input,resolve,reject,branch,rl);

        });
        rl.question(`当前没有创建M${branch?branch.substr(1):branch}分支是否需要创建M分支,输入yes创建，quit退出程序:`,answer=>{

          createMBranch(answer,resolve,reject,branch,rl);

        });
        
      }else { 

        if(!git.mergeM().result)reject(`合并${branch}错误，`);

        if(!git.push().result)reject(`推送M${branch?branch.substr(1):branch}错误，`);

        resolve();

      }

    });

  });

  gitOperatorHook.tapPromise('pushTage',()=>{
    
    return new Promise((resolve,reject)=>{

      let {isAllDone} = git.pushTag(tagName)

      if(isAllDone){

        resolve()

      } else {

        reject('推送标签错误，');

      }

    });

  });

  gitOperatorHook.tapPromise('checkVersionTag',()=>{
    
    return new Promise((resolve,reject)=>{

      let {result} = git.checkVersionTag(lastVersionTag,tagName)

      if(result){

        resolve()

      } else {

        reject(`版本标签错误，上一个版本标签${lastVersionTag}，本次版本标签${tagName}，`);

      }

    });

  });

  // if(finishFlag)
  function call(){

    return  gitOperatorHook.promise();

  }

  await call().then().catch(msg=>{

    rl && rl.close();

    error(msg && msg+'程序退出');

  }).finally(()=>{

      rl.close();

  });

};